/**
 * 点击左侧文件夹，显示文件夹下文件内容
 */

import React from 'react';
import { Balloon, Button } from '@teamix/ui';
import { YunxiaoIcon, YunxiaoTable } from '@alife/devops-ui';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import CommitInfoMedia from 'components/commitInfoMedia';
import WebIdeBtn from '../components/webIdeBtn';
import * as actions from '../../../actions/index';
import track from 'utils/track';
import utils from 'utils';
import { getWebIdeUrl } from 'api';
import { getFeature } from 'utils/features';
import ProjectBreadcrumb from 'components/pathBreadcrumb/breadcrumb.jsx';
import { navigate, navigateOpen } from 'utils/router';
import CloneBtn from '../../repoOverviewInfo/cloneBtn';
import ListEmpty from 'atComponents/ListEmpty';
import FileIcon from 'components/fileIcon';
import FlowBtn from '../../repoOverviewInfo/flowBtn';
import NewAndUploadFile from '../../repoOverviewInfo/newAndUploadFile';
import LfsTag from 'components/lfs/lfsTag';
import intl from '../../../../../../../../../locale';

const { Tooltip } = Balloon;
const { pathResource, resourceSubject } = window.FORCE;

function throttle(fn, threshhold = 500) {
  let timeout;
  let start = new Date();
  return function () {
    const context = this;
    const args = arguments;
    const curr = new Date() - 0;

    clearTimeout(timeout); // 总是干掉事件回调
    if (curr - start >= threshhold) {
      console.log('now', curr, curr - start); // 注意这里相减的结果，都差不多是160左右
      fn.apply(context, args); // 只执行一部分方法，这些方法是在某个时间段内执行一次
      start = curr;
    } else {
      // 让方法在脱离事件后也能执行一次
      timeout = setTimeout(() => {
        fn.apply(context, args);
      }, threshhold);
    }
  };
}

class RightTable extends React.Component {
  componentDidMount() {
    this.dom = document.querySelector('.teamix-layout-content');
    this.dom && this.dom.addEventListener('scroll', this.getShowMaxLine);
  }

  componentWillUnmount() {
    this.dom && this.dom.removeEventListener('scroll', this.getShowMaxLine);
  }

  getShowMaxLine = throttle(() => {
    const clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
    const top = this.dom.scrollTop;
    const num = parseInt((clientHeight + top - 227) / 48, 10);
    this.props.getBatchDataOnScroll(num);
  });

  /** @params path 路径， type 类型 */
  jumpTo = (path, type) => {
    const { defaultExpandedKeys } = this.props;
    if (type === 'tree') {
      // 增加展开项
      if (defaultExpandedKeys.indexOf(path) === -1) {
        const expandedKeys = [...defaultExpandedKeys, path];
        this.props.updateData({
          defaultExpandedKeys: expandedKeys,
          selectedKeys: [path],
        });
      }

      navigate(
        `/${pathResource.fullPath}/tree/${utils.revisionEncodeURI(
          resourceSubject.revision,
        )}/${utils.revisionEncodeURI(path)}`,
      );

      this.props.updateSetSelectedType({
        resourceSubject: {
          subject: 'tree',
          path,
        },
      });

      this.props.getExpandedTreeData(path);
    }
    if (type === 'blob') {
      // TODO: 默认选中项在这里和展开左树未设置生效
      this.props.updateData({
        selectedKeys: [path],
      });

      navigate(
        `/${pathResource.fullPath}/blob/${utils.revisionEncodeURI(
          resourceSubject.revision,
        )}/${utils.revisionEncodeURI(path)}`,
      );

      this.props.updateSetSelectedType({
        resourceSubject: {
          subject: 'blob',
          path,
        },
      });
    }
  };

  goNew = () => {
    const { resourcePath } = this.props;
    const revision = resourceSubject.revision || 'master';
    navigate(
      `/${pathResource.fullPath}/new/${utils.revisionEncodeURI(revision)}/${utils.filepathEncodeURI(
        resourcePath,
      )}`,
    );

    this.props.updateSetSelectedType({
      resourceSubject: {
        subject: 'new',
        path: resourcePath,
      },
    });
  };

  goWebIde = (e, path) => {
    const { revisionType } = resourceSubject;
    e.preventDefault();
    const { projectInfo } = this.props;
    const admin_setting_language = projectInfo && projectInfo.admin_setting_language;
    const template = utils.getAdminSettingLanguage(admin_setting_language);
    getWebIdeUrl({
      filepath: path,
      branch: revisionType === 'branch' ? resourceSubject.revision : '',
      commit: revisionType === 'sha1' ? resourceSubject.revision : '',
      line: '',
      column: '',
      type: template,
      merge_commit: '',
      mergerequestId: '',
    })
      .then((result) => {
        navigateOpen(result.endpoint);
      })
      .catch((err) => {
        console.error(err);
      });
  };

  sortFile = (data) => {
    if (!data || !Array.isArray(data)) return data;
    const tree = [];
    const commit = [];
    const other = [];
    data.forEach((v) => {
      if (v.type === 'tree') {
        tree.push(v);
      } else if (v.type === 'commit') {
        commit.push(v);
      } else {
        other.push(v);
      }
    });
    return tree.concat(commit, other);
  };

  goAddReadme = () => {
    track({
      action: 'new_readme',
      page: 'Repo-Files',
    });
    const defaultBranch = window.FORCE.pathResource.defaultBranch || 'master';
    navigate(`/${pathResource.fullPath}/new/${defaultBranch}?file_name=README.md`);

    this.props.updateSetSelectedType({
      resourceSubject: {
        subject: 'new',
        path: '',
      },
    });
  };

  render() {
    const {
      currentTreeData,
      submodules,
      isLoadingTable,
      lastCommit,
      isInitedLeftTree,
      treeData,
      isLoadingLastCommit,
      ipSetting,
    } = this.props;
    const { role, isArchive } = pathResource;

    return (
      <div className="project-content-body">
        <div className="overview-info">
          <ProjectBreadcrumb isHeader {...this.props} />
          <div>
            {isArchive === 'false' ? (
              <React.Fragment>
                {getFeature('WebIDE.entrance.file') && isInitedLeftTree && treeData.length ? (
                  <WebIdeBtn
                    tooltipText={intl.get({
                      id: 'code-assets.content.routes.table.WebideCanOnlyBePerformed',
                      defaultMessage: '只有分支下才可以进行 WebIDE 操作',
                    })}
                    type="normal"
                    onClick={(e) => {
                      track({
                        action: 'goto_webide',
                        page: 'Repo-Files',
                      });

                      this.goWebIde(e, '');
                    }}
                    style={{ marginRight: 8 }}
                    ipSetting={ipSetting}
                  >
                    WebIDE
                  </WebIdeBtn>
                ) : null}
                {getFeature('module_enable.repository.flow') && <FlowBtn {...this.props} />}
                <CloneBtn {...this.props} />
                <NewAndUploadFile {...this.props} goNew={this.goNew} />
              </React.Fragment>
            ) : null}
          </div>
        </div>
        <div className="file-commit-container">
          <CommitInfoMedia commitInfo={lastCommit} isLoading={isLoadingLastCommit} />
        </div>
        {/* {!isLoadingTable && currentTreeData?.length > 500 && (
          <ListEmpty
            size="small"
            type="card"
            content="文件过多"
            description={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                列表文件过多，请点击左侧文件查看
              </div>
            }
            image="none"
            className="no-content no-btns"
          />
        )} */}
        {/* && currentTreeData?.length < 500 */}
        {!isLoadingTable && (
          <YunxiaoTable
            dataSource={this.sortFile(currentTreeData)}
            hasBorder={false}
            pagination={false}
            className="file-table"
            emptyContent={
              <ListEmpty
                size="small"
                type="card"
                content="暂无内容"
                description={
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <Button type="primary" text onClick={this.goAddReadme}>
                      添加 README
                    </Button>
                    <span>&nbsp;让协作者更好的理解你的工程</span>
                  </div>
                }
                image="none"
                className="no-content no-btns"
              />
            }
            onRowClick={(record) => {
              switch (record.type) {
                case 'tree':
                  this.jumpTo(record.path, 'tree');
                  break;
                case 'blob':
                  this.jumpTo(record.path, 'blob');
                  break;
                case 'commit': {
                  const submodule = submodules.find((item) => item.path === record.path);
                  window.location = submodule.http_homepage_url;
                  break;
                }
                default:
                // no default
              }
            }}
          >
            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.src.utils.locale.Name',
                defaultMessage: '名称',
              })}
              className="file-name-col"
              cell={(value, index, record) => {
                const trigger = (
                  <div className={`table-cell-one-line ${record.is_lfs ? 'lfs' : ''}`}>
                    {record.type !== 'commit' ? (
                      <span>
                        {record.type === 'tree' ? (
                          <YunxiaoIcon type="folder-line" className="file-icon" />
                        ) : (
                          <FileIcon
                            className="file-icon"
                            fileName={record.name}
                            style={{ verticalAlign: 'text-bottom' }}
                          />
                        )}

                        <span style={{ marginLeft: 8 }}>{record.name}</span>
                      </span>
                    ) : (
                      <span>
                        <i className="fa fa-archive" />
                        <span style={{ marginLeft: 8 }}>
                          {record.name}
                          {submodules.find((item) => item.path === record.path) ? (
                            <a
                              href={`${
                                submodules.find((item) => item.path === record.path)
                                  .http_homepage_url
                              }/tree/${record.id}`}
                            >
                              @ {record.id.slice(0, 8)}
                            </a>
                          ) : null}
                        </span>
                      </span>
                    )}
                  </div>
                );

                return (
                  <React.Fragment>
                    <Tooltip trigger={trigger} align="b">
                      {record.name}
                    </Tooltip>
                    {record.is_lfs && <LfsTag role={role} />}
                  </React.Fragment>
                );
              }}
            />

            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.src.utils.locale.RecentlySubmitted',
                defaultMessage: '最近提交',
              })}
              className="file-table-secondary-col file-last-commit-col"
              cell={(value, index, record) => {
                return (
                  <Tooltip
                    trigger={<div className="table-cell-one-line">{record.lastCommit}</div>}
                    align="b"
                  >
                    {record.lastCommit}
                  </Tooltip>
                );
              }}
            />

            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.content.routes.table.Creator',
                defaultMessage: '创建者',
              })}
              className="file-table-secondary-col username-col"
              width={120}
              cell={(value, index, record) => {
                const trigger = <div className="table-cell-one-line">{record.username}</div>;
                return (
                  <Tooltip trigger={trigger} align="b">
                    {record.username}
                  </Tooltip>
                );
              }}
            />

            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.content.routes.table.UpdateTime',
                defaultMessage: '更新时间',
              })}
              className="file-table-secondary-col updatetime-col"
              cell={(value, index, record) => <span>{record.lastUpdate}</span>}
            />
          </YunxiaoTable>
        )}
      </div>
    );
  }
}

export default connect(
  (state) => {
    return { ...state.project.projectFiles, projectInfo: state.project.root.projectInfo };
  },
  (dispatch) => bindActionCreators(actions, dispatch),
)(RightTable);
